﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace UnitTests.Framework
{
	/// <summary>
	/// A static wrapper for .NET's MD5 classes
	/// </summary>
	public static class MD5Handler
	{
		/// <summary>
		/// Hashes a given string using MD5 and outputs a 32 character hex representation of the hash
		/// </summary>
		/// <param name="input">String to hash using MD5</param>
		/// <returns>A 32 hex character string which is the hash</returns>
		public static string Hash(string input)
		{
			byte[] data = null;
			using (MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider())
			{
				data = md5Hasher.ComputeHash(Encoding.ASCII.GetBytes(input));
			}

			StringBuilder sBuilder = new StringBuilder();
			foreach (var item in data)
			{
				sBuilder.Append(item.ToString("x2"));
			}
			return sBuilder.ToString();
		}

		/// <summary>
		/// Verifies the hash of the given input with a given hash
		/// </summary>
		/// <param name="input">Input to hash and compare</param>
		/// <param name="hash">Hash to compare</param>
		/// <returns>True if the input's hash is the same value as the given hash, otherwise false</returns>
		public static bool VerifyHash(string input, string hash)
		{
			return Hash(input).Equals(hash, StringComparison.OrdinalIgnoreCase);
		}
	}
}
